import { defineConfig } from '@vue/cli-service'
import AutoImport from 'unplugin-auto-import/webpack'
import Components from 'unplugin-vue-components/webpack'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/webpack'
import path from 'path'
import { dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
// import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'
import SpeedMeasurePlugin from 'speed-measure-webpack-plugin'

const smp = new SpeedMeasurePlugin()

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const pathSrc = path.resolve(__dirname, 'src')

function resolve(dir) {
  return path.join(__dirname, dir)
}

// 全局 scss 样式, 符合 css 的覆盖规则
const scssGlobalUse = ['@/assets/css/layout/config.scss', '@/assets/css/layout/theme.scss', '@/assets/css/mixin.scss']

export default defineConfig({
  publicPath: process.env.VUE_APP_BASE_URL,
  devServer: {
    proxy: {
      [process.env.VUE_APP_API_URL]: {
        target: 'http://127.0.0.1/', // 你的后端服务器地址
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_API_URL]: '',
        },
      },
    },
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    client: {
      overlay: false,
    },
  },
  css: {
    loaderOptions: {
      scss: {
        additionalData: scssGlobalUse.map((i) => `@use "${i}" as *;`).join('\n'),
        warnRuleAsWarning: false,
      },
    },
  },
  configureWebpack: smp.wrap({
    plugins: [
      AutoImport({
        imports: ['vue', 'vue-router', 'pinia', '@vueuse/core'],
        resolvers: [ElementPlusResolver()],
        ignore: ['useEventBus', 'useWebSocket'],
        eslintrc: {
          enabled: false,
        },
        dts: path.resolve(pathSrc, 'auto-imports.d.ts'),
      }),
      Components({
        dirs: ['src/components', 'src/views', 'src/layout'],
        resolvers: [
          ElementPlusResolver({
            importStyle: 'sass',
          }),
        ],
        dts: path.resolve(pathSrc, 'components.d.ts'),
      }),
      ElementPlus({
        useSource: true,
      }),
      // new BundleAnalyzerPlugin({
      //   analyzerMode: 'static',
      //   openAnalyzer: false,
      //   logLevel: 'silent',
      // }),
    ],
  }),
  productionSourceMap: false,
  chainWebpack(config) {
    config.module.rule('svg').exclude.add(resolve('src/assets/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
      })
      .end()
  },
})
